using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using LinkPointTransaction;
using System.Collections.Specialized;
using System.Configuration;
using SiteManager;
using System.Text;
using System.Data.SqlClient;

public partial class Doctor_doctorUnsubscribe : System.Web.UI.Page
{
    protected string configfile;
    protected string keyfile;
    protected string host;
    protected int port;
    protected bool fLog = false;
    protected int logLvl = 0;

    protected bool fIE5;
    protected string order;
    protected string resp;
    protected string R_Approved;
    protected string R_Time;
    protected string R_Ref;
    protected string R_Code;
    protected string R_Authresr;
    protected string R_Error;
    protected string R_OrderNum;
    protected string R_Message;
    protected string R_Score;
    protected string R_TDate;
    protected string R_AVS;
    protected string R_FraudCode;
    protected string R_ESD;
    protected string R_Tax;
    protected string R_Shipping;


    protected string logFile = "";
    protected string cardnumber = "";
    protected string expmonth = "";
    protected string expyear = "05";
    protected string total = "";
    protected string pbthreshold = "";
    protected string startdate = "";
    protected string periodicity = "";
    protected string installments = "";
    protected string oid = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        localFunction drchk = new localFunction();
        drchk.checkDoctorLogin(true);

        if (!Page.IsPostBack)
        {
            if (Session["userID"].ToString() != "")
            {
                GetOrderDetails();
                //Fill dropdowns
            }
            YearDisplay();
            MonthDisplay();
        }

        if (IsPostBack)
        {
            // Parse form data
            ParseFormData();
            // process order
            ProcessOrder();

            HttpBrowserCapabilities bc = Request.Browser;
            fIE5 = (bc.Browser == "IE" && bc.MajorVersion > 4);

            order = (string)Session["outXml"];
            resp = (string)Session["resp"];
            ParseResponse(resp);

            Response.Write("Transaction Status: " + R_Approved);

            if (R_Approved == "APPROVED")
            {
                //  SaveDataAfterApproval();
                // code for set IsActive false
                //    ObjManager.ExecuteQuery("update coupons set IsActive='false',UsedAsOn=getdate() where couponcode='" + txtCouponCode.Text.ToString() + "' and Fordoctorid='" + iDoctorid + "'");
                //end code

            }


        }
    }

    protected void GetOrderDetails()
    {
        Manager obj = new Manager(true,"ConnectionString");
        string sql = "Select SubscriptionId, TransactionAmount FROM DoctorSubscription WHERE DoctorId = " + Session["userID"];

        //Response.Write(sql);

        SqlDataReader dr = obj.ExecuteQuery(sql);
        if (dr.Read())
        {
            txttotal.Text = dr["TransactionAmount"].ToString();
            txtoid.Text = dr["SubscriptionId"].ToString();
        }
        else
        {
            lblError.Text = "No Monthly Subscribtion found for your Account!";
            lblError.Visible = true;
        }
        dr.Close();
    }

    protected void ParseFormData()
    {
        total = txttotal.Text;
        cardnumber = txtCardNumber.Text;
        expmonth = ddlMonth.SelectedValue.ToString();
        string r = ddlYear.SelectedValue.ToString();
        r = r.Substring(2);
        expyear = r;
        if ((total == null) || total.Length < 1) { total = "0.0"; }
        pbthreshold = "3";
        startdate = "immediate";
        periodicity = "Monthly";// rbSubscription.SelectedItem.ToString();
        installments = "99";
        oid = txtoid.Text;
        GetConfigParams();
    }

    private void GetConfigParams()
    {
        // get some stuff from app config
        // NameValueCollection config1 = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/client"); commented at 131008 to fix
        NameValueCollection config1 = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/client");

        configfile = config1["Configfile"];
        keyfile = config1["Keyfile"];
        host = config1["Host"];
        port = Int32.Parse(config1["Port"]);

        //NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/opts"); commented at 131008 to fix
        NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/opts");

        try
        {
            fLog = bool.Parse(config["fLog"]);
        }
        catch (Exception) { }

        try
        {
            logLvl = Int32.Parse(config["logLvl"]);
        }
        catch (Exception) { }

        try
        {
            logFile = config["logFile"];
        }
        catch (Exception) { }

    }

    private void ProcessOrder()
    {
        // create order
        LPOrderPart order = LPOrderFactory.createOrderPart("order");
        // create a part we will use to build the order
        LPOrderPart op = LPOrderFactory.createOrderPart();

        // Build 'orderoptions'
        op.put("ordertype", "SALE");
        // add 'orderoptions to order
        order.addPart("orderoptions", op);

        // Build 'merchantinfo'
        op.clear();
        op.put("configfile", configfile);
        // add 'merchantinfo to order
        order.addPart("merchantinfo", op);

        // Build 'creditcard'
        op.clear();
        op.put("cardnumber", cardnumber);
        op.put("cardexpmonth", expmonth);
        op.put("cardexpyear", expyear);
        // add 'creditcard to order
        order.addPart("creditcard", op);

        // Build 'payment'
        op.clear();
        op.put("chargetotal", total);
        // add 'payment to order
        order.addPart("payment", op);

        // build 'periodic' part
        op.clear();
        op.put("action", "CANCEL");
        op.put("startdate", startdate);
        op.put("periodicity", periodicity);
        op.put("installments", installments);
        op.put("threshold", pbthreshold);
        // add 'periodic' to order
        order.addPart("periodic", op);

        // Add oid
        op.clear();
        op.put("oid", oid);
        // add 'transactiondetails to order
        order.addPart("transactiondetails", op);

        // create transaction object  
        LinkPointTxn LPTxn = new LinkPointTxn();

        // get outgoing XML from the 'order' object
        string outXml = order.toXML();

        // Call LPTxn
        string resp = LPTxn.send(keyfile, host, port, outXml);

        //Store transaction data on Session and redirect
        Session["outXml"] = outXml;
        Session["resp"] = resp;
        Server.Transfer("unstatus.aspx");

    }


    private void YearDisplay()
    {
        ddlYear.Items.Insert(0, "Year");
        for (int i = 2007; i < 2013; i++)
        {
            ddlYear.Items.Add(i.ToString());
        }
    }
    private void MonthDisplay()
    {
        DataTable tbMonth = new DataTable();
        tbMonth.Columns.Add(new DataColumn("MonthNo"));
        tbMonth.Columns.Add(new DataColumn("MonthName"));
        tbMonth.Rows.Add(new object[] { "01", "Jan" });
        tbMonth.Rows.Add(new object[] { "02", "Feb" });
        tbMonth.Rows.Add(new object[] { "03", "Mar" });
        tbMonth.Rows.Add(new object[] { "04", "Apr" });
        tbMonth.Rows.Add(new object[] { "05", "May" });
        tbMonth.Rows.Add(new object[] { "06", "Jun" });
        tbMonth.Rows.Add(new object[] { "07", "July" });
        tbMonth.Rows.Add(new object[] { "08", "Aug" });
        tbMonth.Rows.Add(new object[] { "09", "Sep" });
        tbMonth.Rows.Add(new object[] { "10", "Oct" });
        tbMonth.Rows.Add(new object[] { "11", "Nov" });
        tbMonth.Rows.Add(new object[] { "12", "Dec" });
        ddlMonth.DataSource = tbMonth;
        ddlMonth.DataValueField = "MonthNo";
        ddlMonth.DataTextField = "MonthName";
        ddlMonth.DataBind();
        ddlMonth.Items.Insert(0, "Month");

    }

    protected void ParseResponse(string rsp)
    {
        R_Time = ParseTag("r_time", rsp);
        R_Ref = ParseTag("r_ref", rsp);
        R_Approved = ParseTag("r_approved", rsp);
        R_Code = ParseTag("r_code", rsp);
        R_Authresr = ParseTag("r_authresronse", rsp);
        R_Error = ParseTag("r_error", rsp);
        R_OrderNum = ParseTag("r_ordernum", rsp);
        R_Message = ParseTag("r_message", rsp);
        R_Score = ParseTag("r_score", rsp);
        R_TDate = ParseTag("r_tdate", rsp);
        R_AVS = ParseTag("r_avs", rsp);
        R_Tax = ParseTag("r_tax", rsp);
        R_Shipping = ParseTag("r_shipping", rsp);
        R_FraudCode = ParseTag("r_fraudCode", rsp);
        R_ESD = ParseTag("esd", rsp);
    }

    protected string ParseTag(string tag, string rsp)
    {
        StringBuilder sb = new StringBuilder(256);
        sb.AppendFormat("<{0}>", tag);
        int len = sb.Length;
        int idxSt = -1, idxEnd = -1;
        if (-1 == (idxSt = rsp.IndexOf(sb.ToString())))
        { return ""; }
        idxSt += len;
        sb.Remove(0, len);
        sb.AppendFormat("</{0}>", tag);
        if (-1 == (idxEnd = rsp.IndexOf(sb.ToString(), idxSt)))
        { return ""; }
        return rsp.Substring(idxSt, idxEnd - idxSt);
    }
}
